import time
from typing import Optional, Callable
from Logger import Logger

logger = Logger.get_logger(__name__)

class WaitUtils:
    """
    Utility class providing waiting functionality.
    Supports both synchronous and asynchronous waiting.
    """
    
    @staticmethod
    def wait(seconds: float) -> None:
        """
        Synchronously wait for specified number of seconds
        
        Args:
            seconds: Number of seconds to wait
        """
        time.sleep(seconds)
    
    @staticmethod
    def wait_until(condition: Callable[[], bool], timeout: float = 60.0, poll_interval: float = 0.1) -> bool:
        """
        Wait until a condition is met or timeout occurs
        
        Args:
            condition: Function that returns True when condition is met
            timeout: Maximum time to wait in seconds
            poll_interval: Time between condition checks in seconds
            
        Returns:
            bool: True if condition was met, False if timeout occurred
        """
        try:
            start_time = time.time()
            while time.time() - start_time < timeout:
                if condition():
                    return True
                time.sleep(poll_interval)
            return False
        except Exception as e:
            logger.error(f"Error while waiting for condition: {str(e)}")
            return False
    
    @staticmethod
    def wait_with_callback(seconds: float, callback: Optional[Callable[[float], None]] = None) -> None:
        """
        Wait with progress callback
        
        Args:
            seconds: Number of seconds to wait
            callback: Optional function called with progress (0.0 to 1.0)
        """
        try:
            start_time = time.time()
            while True:
                elapsed = time.time() - start_time
                if elapsed >= seconds:
                    if callback:
                        callback(1.0)
                    break
                    
                if callback:
                    callback(elapsed / seconds)
                time.sleep(0.1)
        except Exception as e:
            logger.error(f"Error during wait with callback: {str(e)}")
